package com.hand.wfive.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.CSJAdError;
import com.bytedance.sdk.openadsdk.CSJSplashAd;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.hand.wfive.BuildConfig;
import com.hand.wfive.R;
import com.hand.wfive.ad.AdActivity;
import com.hand.wfive.ad.AdConfig;
import com.hand.wfive.ad.TTAdManagerHolder;
import com.hand.wfive.ad.UIUtils;
import com.hand.wfive.base.BaseActivity;
import com.hand.wfive.loginAndVip.ApiConfig;
import com.hand.wfive.loginAndVip.LoginConfig;
import com.hand.wfive.loginAndVip.UserManager;
import com.hand.wfive.loginAndVip.model.AdConfigModel;
import com.hand.wfive.util.FuncSwitchUtils;
import com.rxjava.rxlife.RxLife;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import java.util.Map;

import butterknife.BindView;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.observers.ResourceObserver;
import rxhttp.wrapper.param.RxHttp;

public class LauncherActivity extends BaseActivity {

    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.splash_container)
    FrameLayout mSplashContainer;

    private int loadCount = 1;
    private static final int AD_TIME_OUT = 3000;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_launcher;
    }

    @Override
    protected void init() {
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }

        initUmeng();
        FuncSwitchUtils.getSwitchValue();
        AdActivity.lastWatchVideo = 0;
        AdActivity.lastShowBanner = 0;
        if (LoginConfig.ShowQQ) LoginConfig.getQQ();
        UserManager.getInstance().initUser(false);
        if (AdConfig.isShowAd) {
            if ("1".equals(AdConfig.getAdAppId()) || TextUtils.isEmpty(AdConfig.getSplashCodeId())) {
                queryAdMethod();
            } else {
                initAdConfig();
            }
        } else {
            showMain(false);
        }
    }

    private void queryAdMethod() {
        RxHttp.postForm(ApiConfig.queryConfigByKey)
                .add("key", BuildConfig.APPLICATION_ID)
                .asClass(AdConfigModel.class)
                .to(RxLife.toMain(this))  //感知生命周期，并在主线程回调
                .subscribe(new ResourceObserver<AdConfigModel>() {
                    @Override
                    public void onNext(@NonNull AdConfigModel apiModel) {
                        if (apiModel.getCode() == ApiConfig.SUCCESSCODE) {
                            Map<String, String> adConfigEntity = apiModel.getObj();
                            if (adConfigEntity != null) {

                                // 广告配置获取
                                AdConfig.setAdAppId(adConfigEntity.get("appName"));//广告id
                                AdConfig.setSplashCodeId(adConfigEntity.get("huawei"));//开屏广告id
                                AdConfig.setVideoCodeId(adConfigEntity.get("vivo"));//视频广告id
                                AdConfig.setDialogCodeId(adConfigEntity.get("xiaomi"));//弹窗广告id
                                AdConfig.setBannerCodeId(adConfigEntity.get("oppo"));//banner广告id

                                // 广告模式
                                AdConfig.vacation = apiModel.getVacationNormal();
                                /**
                                 * 单个App广告模式控制
                                 * 0:上班模式
                                 * 1:下班模式
                                 * 2:节假日模式
                                 * 3:无广告
                                 * 4:无开屏
                                 * 5:无banner
                                 * */
                                String adMode = adConfigEntity.get("adMode");
                                if ("1".equals(adMode)) {
                                    AdConfig.vacation = AdConfig.VACATION_OFF_WORK;
                                } else if ("2".equals(adMode)) {
                                    AdConfig.vacation = AdConfig.VACATION_HOLIDAY;
                                } else if ("3".equals(adMode)) {
                                    AdConfig.vacation = AdConfig.VACATION_NO_AD;
                                } else if ("4".equals(adMode)) {
                                    AdConfig.vacation = AdConfig.VACATION_OFF_WORK_NOSPLASHAD;
                                } else if ("5".equals(adMode)) {
                                    AdConfig.vacation = AdConfig.VACATION_OFF_WORK_NOBANNERAD;
                                }

                                /**
                                 * 全局广告总开关
                                 * 0：广告开启
                                 * 1：广告关闭
                                 */
                                if (apiModel.getCloseAd() == 1 || AdConfig.vacation ==AdConfig.VACATION_NO_AD) {
                                    AdConfig.adDisable = true;
                                }

                                String status = adConfigEntity.get("status");
                                if ("0".equals(status)) {
                                    AdActivity.WatchVideoDelay = 2 * 60 * 1000;
                                    AdConfig.vacation = AdConfig.VACATION_WORKING;
                                } else {
                                    if (AdConfig.vacation == AdConfig.VACATION_WORKING) {
                                        AdActivity.WatchVideoDelay = 2 * 60 * 1000;
                                    } else if (AdConfig.vacation == AdConfig.VACATION_OFF_WORK) {
                                        AdActivity.WatchVideoDelay = 60 * 1000;
                                    } else if (AdConfig.vacation == AdConfig.VACATION_HOLIDAY) {
                                        AdActivity.WatchVideoDelay = 30 * 1000;
                                    }
                                }

                                /**
                                 * 是否显示开屏广告
                                 * zol如果不为空就不显示开屏广告
                                 * 广告模式为VACATION_OFF_WORK_NOSPLASHAD也不展示开屏广告
                                 * */
                                String zol = adConfigEntity.get("zol");
                                if (!TextUtils.isEmpty(zol) || AdConfig.vacation == AdConfig.VACATION_OFF_WORK_NOSPLASHAD) {
                                    AdConfig.isShowSplashAd = !AdConfig.isHuawei();
                                } else {
                                    AdConfig.isShowSplashAd = true;
                                }

                            } else {
                                AdConfig.adDisable = apiModel.getCloseAd() == 1;
                            }
                        } else {
                            AdConfig.adDisable = apiModel.getCloseAd() == 1;
                        }
                        showMain();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (loadCount > 2) {
                            showMain();
                        } else {
                            loadCount++;
                            queryAdMethod();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initAdConfig() {
        RxHttp.postForm(ApiConfig.queryConfigByKey)
                .add("key", AdConfig.getAdAppId())
                .asClass(AdConfigModel.class)
                .to(RxLife.toMain(this))
                .subscribe(new ResourceObserver<AdConfigModel>() {
                    @Override
                    public void onNext(@NonNull AdConfigModel apiModel) {
                        if (apiModel.getCode() == ApiConfig.SUCCESSCODE) {
                            Map<String, String> adConfigEntity = apiModel.getObj();
                            if (adConfigEntity != null) {
                                // 单个App广告控制
                                String status = adConfigEntity.get("status");
                                if ("0".equals(status) && BuildConfig.VERSION_NAME.equalsIgnoreCase(adConfigEntity.get(getString(R.string.channel)))) {
                                    AdConfig.adDisable = true;
                                }

                                /**
                                 * 广告模式
                                 */
                                AdConfig.vacation = apiModel.getVacationNormal();
                                /**
                                 * 单个App广告模式控制
                                 * 0:上班模式
                                 * 1:下班模式
                                 * 2:节假日模式
                                 * 3:无广告
                                 * 4:无开屏
                                 * 5:无banner
                                 * */
                                String adMode = adConfigEntity.get("adMode");
                                if ("1".equals(adMode)) {
                                    AdConfig.vacation = AdConfig.VACATION_OFF_WORK;
                                } else if ("2".equals(adMode)) {
                                    AdConfig.vacation = AdConfig.VACATION_HOLIDAY;
                                } else if ("3".equals(adMode)) {
                                    AdConfig.vacation = AdConfig.VACATION_NO_AD;
                                } else if ("4".equals(adMode)) {
                                    AdConfig.vacation = AdConfig.VACATION_OFF_WORK_NOSPLASHAD;
                                } else if ("5".equals(adMode)) {
                                    AdConfig.vacation = AdConfig.VACATION_OFF_WORK_NOBANNERAD;
                                }
                                /**
                                 * 全局广告总开关
                                 * 0：广告开启
                                 * 1：广告关闭
                                 */
                                if (apiModel.getCloseAd() == 1 || AdConfig.vacation ==AdConfig.VACATION_NO_AD) {
                                    AdConfig.adDisable = true;
                                }

                                if ("0".equals(status)) {
                                    AdActivity.WatchVideoDelay = 2 * 60 * 1000;
                                    AdConfig.vacation = AdConfig.VACATION_WORKING;
                                } else {
                                    if (AdConfig.vacation == AdConfig.VACATION_WORKING) {
                                        AdActivity.WatchVideoDelay = 2 * 60 * 1000;
                                    } else if (AdConfig.vacation == AdConfig.VACATION_OFF_WORK) {
                                        AdActivity.WatchVideoDelay = 60 * 1000;
                                    } else if (AdConfig.vacation == AdConfig.VACATION_HOLIDAY) {
                                        AdActivity.WatchVideoDelay = 30 * 1000;
                                    }
                                }

                                /**
                                 * 是否显示开屏广告
                                 * zol如果不为空就不显示开屏广告
                                 * 广告模式为VACATION_OFF_WORK_NOSPLASHAD也不展示开屏广告
                                 */
                                String zol = adConfigEntity.get("zol");
                                if (!TextUtils.isEmpty(zol) || AdConfig.vacation == AdConfig.VACATION_OFF_WORK_NOSPLASHAD) {
                                    AdConfig.isShowSplashAd = !AdConfig.isHuawei();
                                } else {
                                    AdConfig.isShowSplashAd = true;
                                }

                            } else {
                                AdConfig.adDisable = apiModel.getCloseAd() == 1;
                            }
                        } else {
                            AdConfig.adDisable = apiModel.getCloseAd() == 1;
                        }
                        showMain();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (loadCount > 2) {
                            showMain();
                        } else {
                            loadCount++;
                            initAdConfig();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 加载开屏广告
     */
    private void loadSplashAd() {
        if (!TTAdManagerHolder.isInitAndReady()) return;

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(dm);

        int splashWidthPx = UIUtils.getScreenWidthInPx(this);
        int splashHeightPx = UIUtils.getScreenHeight(this);

        float splashWidthDp = UIUtils.getScreenWidthDp(this);
        float splashHeightDp = UIUtils.px2dip(this, splashHeightPx);

        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(AdConfig.getSplashCodeId())
                .setExpressViewAcceptedSize(splashWidthDp, splashHeightDp) // 单位是dp
                .setImageAcceptedSize(splashWidthPx, splashHeightPx) // 单位是px
                .build();

        TTAdNative mTTAdNative = TTAdManagerHolder.get().createAdNative(this);
        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.CSJSplashAdListener() {

            @Override
            public void onSplashLoadSuccess(CSJSplashAd csjSplashAd) {

            }

            @Override
            public void onSplashLoadFail(CSJAdError error) {
                goToMainActivity();
            }

            @Override
            public void onSplashRenderSuccess(CSJSplashAd ad) {
                if (ad == null) {
                    return;
                }
                mSplashContainer.setVisibility(View.VISIBLE);
                ad.showSplashView(mSplashContainer);
                ad.setSplashAdListener(new CSJSplashAd.SplashAdListener() {
                    @Override
                    public void onSplashAdShow(CSJSplashAd ad) {
                        Log.d(AdConfig.AD_LOG_TAG, "onAdShow");
                    }

                    @Override
                    public void onSplashAdClick(CSJSplashAd ad) {
                        Log.d(AdConfig.AD_LOG_TAG, "onAdClicked");
                    }

                    @Override
                    public void onSplashAdClose(CSJSplashAd ad, int closeType) {
                        goToMainActivity();
                    }
                });
            }

            @Override
            public void onSplashRenderFail(CSJSplashAd ad, CSJAdError csjAdError) {
                goToMainActivity();
            }
        }, AD_TIME_OUT);

    }

    private void initUmeng() {
        UMConfigure.init(this, LoginConfig.UmengId, getString(R.string.channel), UMConfigure.DEVICE_TYPE_PHONE, "");
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
    }

    private void showMain() {
        showMain(true);
    }

    private void showMain(boolean loadSplashAd) {
        if (TextUtils.isEmpty(AdConfig.getSplashCodeId())) {
            AdConfig.adDisable = true;
        }
        new Handler(getMainLooper()).postDelayed(() -> {
            Log.i(AdConfig.AD_LOG_TAG, "开始初始化");
            TTAdManagerHolder.init(new TTAdSdk.Callback() {
                @Override
                public void success() {
                    Log.i(AdConfig.AD_LOG_TAG, "初始化成功");
                    runOnUiThread(() -> {
                        if (AdConfig.isShowSplashAd && loadSplashAd && !AdConfig.adDisable) {
                            loadSplashAd();
                        } else {
                            goToMainActivity();
                        }
                    });
                }

                @Override
                public void fail(int i, String s) {
                    Log.i(AdConfig.AD_LOG_TAG, "初始化失败");
                    AdConfig.adDisable = true;
                    runOnUiThread(() -> goToMainActivity());
                }
            });
        }, 500);
    }

    /**
     * 跳转到主页面
     */
    private void goToMainActivity() {
        MainActivity.show(mContext);
//        Intent intent = new Intent(mContext, MainActivity.class);
//        startActivity(intent);
        this.finish();
    }

    @Override
    protected void onDestroy() {
        if (mSplashContainer != null) {
            mSplashContainer.removeAllViews();
        }
        super.onDestroy();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }
}
